/*
 * JBeagle - a Java toolkit for genetic algorithms.
 * 
 * Copyright (c) 2010 Matthijs Snel
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package jbeagle.core;

import java.util.ArrayList;
import java.util.Collection;

public class Population<I extends Individual<G>, G> extends ArrayList<I> {

	private static final long serialVersionUID = -7695844293785468444L;
	
	protected double avgFitness;
	protected I fittest;
	
	public Population() {
		super();
	}
	
	public Population( int size ) {
		super( size );
	}
	
	public Population( int size, IndividualFactory<I, G> f ) {
		super( size );
		init(size, f);
	}
	
	public Population( Collection<? extends I> c ) {
		super(c);	
	}
	
	public double getAvgFitness() {
		return avgFitness;
	}
	
	public I getFittest() {
		//System.out.println("Returning " + fittest);
		return fittest;
	}
	
	public void init( int size, IndividualFactory<I, G> f ) {
		clear();
		for( int i = 0; i < size; i++ )
			add( f.createIndividual() );
	}
	
	@Override
	public String toString() {
		String s = "";
		for ( I ind : this )
			s += ind + ", " + ind.getFitness() + "\n";
		return s;
	}
	
	public void updateFitness() {
		double total = 0, best = Double.NEGATIVE_INFINITY, curr = 0;
		for ( I ind : this ) {
			curr = ind.getFitness();
			total += curr;
			if ( curr > best ) {
				fittest = ind;
				best = curr;
			}
		}
		avgFitness = total / size();
	}
}
